package com.sykj.manage.web;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sykj.manage.model.Sys_User;
import com.sykj.manage.service.SysUserService;
import com.sykj.util.MD5Util;

@Controller
@RequestMapping("/shiro")
public class LoginController {
	
	@Autowired
	SysUserService sysUserService;
	
	@RequestMapping("/login")
	@ResponseBody
	public String login(String account,String password) {
		//SecurityUtils 是 securityManager的辅助工具获得当前用户
		//获取当前用户主体
		System.out.println(account+"======"+password);
		String result = "{\"appcode\":\"%s\", \"appmsg\":\"%s\" }";
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			//创建账号密码对象
			UsernamePasswordToken token = new UsernamePasswordToken(account, password);
			System.out.println("====="+token);
			try{
				//登陆认证操作
				currentUser.login(token);
				System.out.println("登陆成功");
				result = String.format(result, "1","Success!");
				return result;
				
			}catch (AuthenticationException ae){ 
				ae.printStackTrace();
				System.out.println("登陆失败");
				result = String.format(result, "0","Failed！");
				return result;
			   }
		}else {
			result = String.format(result, "1","Success!");
		}
		return result;
	}
	
	@RequestMapping("/logout")
	public String logout(String username,String password) {
		//SecurityUtils 是 securityManager的辅助工具获得当前用户
		//获取当前用户主体
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			currentUser.logout();
		}
		return "login";
	}
	@RequestMapping("/index")
	public String logout() {
		return "manage/index.html";
	}
	
}
